var protocol = require('pomelo-protocol');
var Package = protocol.Package;
var logger = require('pomelo-logger').getLogger('pomelo', __filename);

var handlers = {};

var ST_INITED = 0;
var ST_WAIT_ACK = 1;
var ST_WORKING = 2;
var ST_CLOSED = 3;

var handleHandshake = function(socket, pkg) {//握手
	if(socket.state !== ST_INITED) {
    return;
  }
	socket.emit('handshake', JSON.parse(protocol.strdecode(pkg.body)));//抛出握手事件
};

var handleHandshakeAck = function(socket, pkg) {//客户端发来的握手ack
	if(socket.state !== ST_WAIT_ACK) {//如果socket状态不是等待握手ack
    return;
  }
  socket.state = ST_WORKING;//改变socket状态为工作中
	socket.emit('heartbeat');//发送第一个心跳
};

var handleHeartbeat = function(socket, pkg) {//心跳
	if(socket.state !== ST_WORKING) {
    return;
  }
	socket.emit('heartbeat');
};

var handleData = function(socket, pkg) {//数据    
	if(socket.state !== ST_WORKING) {
    return;
  }
	socket.emit('message', pkg);//这里发送了message信息 这里的socket是更高层抽象的socket 比如hybridsocket.js
};

handlers[Package.TYPE_HANDSHAKE] = handleHandshake;
handlers[Package.TYPE_HANDSHAKE_ACK] = handleHandshakeAck;
handlers[Package.TYPE_HEARTBEAT] = handleHeartbeat;
handlers[Package.TYPE_DATA] = handleData;

var handle = function(socket, pkg) {
  var handler = handlers[pkg.type];//根据数据包类型取得处理函数  可能会出错！！当pkg是个数组的时候
  if(!!handler) {//如果处理函数存在
    handler(socket, pkg);//调用处理函数处理
  }	else {
    logger.error('could not find handle invalid data package.');//找不到处理函数 错误的数据包
    socket.disconnect();//断开连接
  }
};

module.exports = handle;